<template>
  <div class="card content-box">
    <div class="detail-header">
      <h2>工单详情</h2>
      <el-button @click="handleBack">返回列表</el-button>
    </div>

    <div v-loading="loading" class="detail-content">
      <!-- 基本信息 -->
      <div class="info-section">
        <h3>基本信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单编码">
            {{ workOrderDetail.workOrderCode || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="工单类型">
            <el-tag :type="getWorkOrderTypeTagType(workOrderDetail.workOrderType)">
              {{ getWorkOrderTypeText(workOrderDetail.workOrderType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="产品型号">
            {{ workOrderDetail.productCode || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="产品名称">
            {{ workOrderDetail.productName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="工单状态">
            <el-tag :type="getStatusType(workOrderDetail.status)">
              {{ getStatusText(workOrderDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="计划数量">
            {{ workOrderDetail.plannedQuantity || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="完成数量">
            {{ workOrderDetail.completedQuantity || 0 }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 返工信息（仅返工工单显示） -->
      <div class="info-section" v-if="isReworkOrder">
        <h3>返工信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="原工单ID">
            {{ workOrderDetail.originalWorkOrderId || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="原工单编码">
            <el-link 
              v-if="workOrderDetail.originalWorkOrderCode" 
              type="primary" 
              @click="viewOriginalWorkOrder"
            >
              {{ workOrderDetail.originalWorkOrderCode }}
            </el-link>
            <span v-else>-</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 生产信息 -->
      <div class="info-section">
        <h3>生产信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工艺路线">
            {{ workOrderDetail.routeName || workOrderDetail.routeCode || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="产线">
            {{ workOrderDetail.productionLineName || workOrderDetail.productionLineCode || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="计划开始时间">
            {{ formatDateTime(workOrderDetail.plannedStartTime) || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="计划结束时间">
            {{ formatDateTime(workOrderDetail.plannedEndTime) || '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 时间信息 -->
      <div class="info-section">
        <h3>时间信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(workOrderDetail.createdTime) || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDateTime(workOrderDetail.updatedTime) || '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 备注信息 -->
      <div class="info-section" v-if="workOrderDetail.remarks">
        <h3>备注信息</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="备注">
            <div class="remarks-content">{{ workOrderDetail.remarks }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-buttons" v-if="workOrderDetail.id">
        <el-button type="primary" @click="handleEdit">编辑工单</el-button>
        
        <!-- 根据状态显示不同操作按钮 -->
        <el-button v-if="workOrderDetail.status === 'initialized'" type="success" @click="handleRelease">下达工单</el-button>
        <el-button v-if="workOrderDetail.status === 'released'" type="warning" @click="handleStart">开始生产</el-button>
        <el-button v-if="workOrderDetail.status === 'started'" type="warning" @click="handleSuspend">暂停工单</el-button>
        <el-button v-if="workOrderDetail.status === 'suspended'" type="success" @click="handleResume">恢复生产</el-button>
        <el-button v-if="workOrderDetail.status === 'started'" type="success" @click="handleComplete">完成工单</el-button>
        <el-button v-if="workOrderDetail.status === 'completed'" type="info" @click="handleClose">关闭工单</el-button>
        <el-button v-if="['initialized', 'released'].includes(workOrderDetail.status || '')" type="danger" @click="handleCancel">取消工单</el-button>
        
        <!-- 返工工单按钮 -->
        <el-button v-if="canCreateReworkOrder" type="warning" @click="handleCreateReworkOrder">创建返工工单</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="workOrderDetail">
import { ref, reactive, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getWorkOrderById,
  releaseWorkOrder,
  startWorkOrder,
  suspendWorkOrder,
  resumeWorkOrder,
  completeWorkOrder,
  closeWorkOrder,
  cancelWorkOrder,
  type WorkOrder
} from "@/api/modules/workorder";

const route = useRoute();
const router = useRouter();
const loading = ref(false);

// 工单详情数据
const workOrderDetail = reactive<Partial<WorkOrder.WorkOrderListItem>>({});

// 计算属性：是否为返工工单
const isReworkOrder = computed(() => {
  return workOrderDetail.workOrderType === 'rework';
});

// 计算属性：是否可以创建返工工单
const canCreateReworkOrder = computed(() => {
  return workOrderDetail.status === 'completed' && workOrderDetail.workOrderType !== 'rework';
});

// 获取状态类型
const getStatusType = (status?: string): "success" | "primary" | "warning" | "info" | "danger" => {
  if (!status) return 'info';
  const statusMap: Record<string, "success" | "primary" | "warning" | "info" | "danger"> = {
    'initialized': 'info',
    'released': 'warning',
    'started': 'primary',
    'suspended': 'warning',
    'completed': 'success',
    'closed': 'info',
    'cancelled': 'danger'
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status?: string): string => {
  if (!status) return '-';
  const statusMap: Record<string, string> = {
    'initialized': '初始化',
    'released': '已下达',
    'started': '生产中',
    'suspended': '已暂停',
    'completed': '已完成',
    'closed': '已关闭',
    'cancelled': '已取消'
  };
  return statusMap[status] || status;
};

// 获取工单类型标签类型
const getWorkOrderTypeTagType = (type?: string): "success" | "primary" | "warning" | "info" | "danger" => {
  if (!type) return 'info';
  const typeMap: Record<string, "success" | "primary" | "warning" | "info" | "danger"> = {
    'production': 'primary',
    'rework': 'warning',
    'trial': 'info',
    'outsourcing': 'success',
    'maintenance': 'danger',
    'sample': 'info',
    'engineering_change': 'warning'
  };
  return typeMap[type] || 'info';
};

// 获取工单类型文本
const getWorkOrderTypeText = (type?: string): string => {
  if (!type) return '-';
  const typeMap: Record<string, string> = {
    'production': '标准生产工单',
    'rework': '返工工单',
    'trial': '试产工单',
    'outsourcing': '外协工单',
    'maintenance': '维修工单',
    'sample': '样品工单',
    'engineering_change': '工程变更工单'
  };
  return typeMap[type] || type;
};

// 格式化日期时间
const formatDateTime = (dateTime?: string | Date | number[]): string => {
  if (!dateTime) return '';
  
  try {
    let date: Date;
    
    if (Array.isArray(dateTime)) {
      // 处理数组格式的日期 [year, month, day, hour, minute, second]
      const [year, month, day, hour = 0, minute = 0, second = 0] = dateTime;
      date = new Date(year, month - 1, day, hour, minute, second);
    } else if (typeof dateTime === 'string') {
      date = new Date(dateTime);
    } else {
      date = dateTime;
    }
    
    if (isNaN(date.getTime())) {
      return '';
    }
    
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch (error) {
    console.error('日期格式化失败:', error);
    return '';
  }
};

// 获取工单详情
const getWorkOrderDetail = async (id: string) => {
  loading.value = true;
  try {
    const res = await getWorkOrderById(id);
    Object.assign(workOrderDetail, res.data);
  } catch (error) {
    console.error('获取工单详情失败:', error);
    ElMessage.error('获取工单详情失败');
    router.push('/workorder');
  } finally {
    loading.value = false;
  }
};

// 返回列表
const handleBack = () => {
  router.push('/workorder');
};

// 编辑工单
const handleEdit = () => {
  router.push(`/workorder/form?id=${workOrderDetail.id}`);
};

// 下达工单
const handleRelease = async () => {
  try {
    await releaseWorkOrder(workOrderDetail.id!);
    ElMessage.success('工单下达成功');
    getWorkOrderDetail(workOrderDetail.id!);
  } catch (error) {
    console.error('工单下达失败:', error);
    ElMessage.error('工单下达失败');
  }
};

// 开始工单
const handleStart = async () => {
  try {
    await startWorkOrder(workOrderDetail.id!);
    ElMessage.success('工单开始成功');
    getWorkOrderDetail(workOrderDetail.id!);
  } catch (error) {
    console.error('工单开始失败:', error);
    ElMessage.error('工单开始失败');
  }
};

// 暂停工单
const handleSuspend = async () => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入暂停原因', '暂停工单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '暂停原因不能为空'
    });
    
    await suspendWorkOrder(workOrderDetail.id!, { suspendReason: reason });
    ElMessage.success('工单暂停成功');
    getWorkOrderDetail(workOrderDetail.id!);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工单暂停失败:', error);
      ElMessage.error('工单暂停失败');
    }
  }
};

// 恢复工单
const handleResume = async () => {
  try {
    await resumeWorkOrder(workOrderDetail.id!);
    ElMessage.success('工单恢复成功');
    getWorkOrderDetail(workOrderDetail.id!);
  } catch (error) {
    console.error('工单恢复失败:', error);
    ElMessage.error('工单恢复失败');
  }
};

// 完成工单
const handleComplete = async () => {
  try {
    const { value: quantity } = await ElMessageBox.prompt(
      `计划数量：${workOrderDetail.plannedQuantity}，请输入完成数量`, 
      '完成工单', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+$/,
        inputErrorMessage: '请输入有效的数量'
      }
    );
    
    await completeWorkOrder(workOrderDetail.id!, { completedQuantity: parseInt(quantity) });
    ElMessage.success('工单完成成功');
    getWorkOrderDetail(workOrderDetail.id!);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工单完成失败:', error);
      ElMessage.error('工单完成失败');
    }
  }
};

// 关闭工单
const handleClose = async () => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入关闭原因', '关闭工单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '关闭原因不能为空'
    });
    
    await closeWorkOrder(workOrderDetail.id!, { closeReason: reason });
    ElMessage.success('工单关闭成功');
    getWorkOrderDetail(workOrderDetail.id!);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工单关闭失败:', error);
      ElMessage.error('工单关闭失败');
    }
  }
};

// 取消工单
const handleCancel = async () => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入取消原因', '取消工单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '取消原因不能为空'
    });
    
    await cancelWorkOrder(workOrderDetail.id!, { cancelReason: reason });
    ElMessage.success('工单取消成功');
    getWorkOrderDetail(workOrderDetail.id!);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工单取消失败:', error);
      ElMessage.error('工单取消失败');
    }
  }
};

// 创建返工工单
const handleCreateReworkOrder = () => {
  router.push(`/workorder/form?type=rework&originalId=${workOrderDetail.id}`);
};

// 查看原工单
const viewOriginalWorkOrder = () => {
  if (workOrderDetail.originalWorkOrderId) {
    router.push(`/workorder/detail/${workOrderDetail.originalWorkOrderId}`);
  }
};

// 页面初始化
onMounted(() => {
  const id = route.params.id as string;
  if (id) {
    getWorkOrderDetail(id);
  } else {
    ElMessage.error('工单ID不能为空');
    router.push('/workorder');
  }
});
</script>

<style scoped>
.content-box {
  padding: 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.detail-header h2 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

.detail-content {
  min-height: 400px;
}

.info-section {
  margin-bottom: 24px;
}

.info-section h3 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}

.remarks-content {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
  max-height: 200px;
  overflow-y: auto;
}

.action-buttons {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  width: 140px;
}

:deep(.el-descriptions__content) {
  word-break: break-word;
}

:deep(.el-link) {
  font-weight: 500;
}
</style>